package cosplay.Services;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class PhotoServices {
	public static int getwidth(byte[] input)
	{
		if (input.length<=0)
			return 0;
		InputStream in=new ByteArrayInputStream(input);
		try {
			Image img=ImageIO.read(in);
			if (img.getWidth(null)<=0)
				return 0;
			return img.getWidth(null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	public static int getHeight(byte[] input)
	{
		if (input.length<=0)
			return 0;
		InputStream in=new ByteArrayInputStream(input);
		try {
			Image img=ImageIO.read(in);
			if (img.getHeight(null)<=0)
				return 0;
			return img.getHeight(null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;		
	}
	public static byte[] getpreview(byte[] input)
	{
		return getpreview(input, 114, 77);
	}
	public static byte[] getpreview(byte[] input,int width, int height)
	{
		InputStream in=new ByteArrayInputStream(input);
		try {
			Image img=ImageIO.read(in);
			if (img==null)
				return null;
			if (img.getWidth(null)<=0)
				return null;
			float wrate=img.getWidth(null)/width;
			float hrate=img.getHeight(null)/height;
			if (wrate>hrate)
			{
				height=Float.valueOf(height*hrate/wrate).intValue();
			}
			else
			{
				width=Float.valueOf(width*wrate/hrate).intValue();				
			}
			BufferedImage tag = new BufferedImage(width , height, BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,0,null);
			ByteArrayOutputStream out=new ByteArrayOutputStream();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			byte[] res=out.toByteArray();
			out.close();
			return res;			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
